package com.example.administrator.newjiajiesong.test;

import com.example.administrator.newjiajiesong.network.http.LifeTreeAPIException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import io.reactivex.observers.DefaultObserver;
import retrofit2.HttpException;

/**
 * Created by: xudiwei
 * <p>
 * on: 2017/4/24.
 * <p>
 * 描述：http Observer
 */

public abstract class HttpObserver<T> extends DefaultObserver<T> {

    public abstract void onSuccess(T t);

    public abstract void onFailed(int code, String msg);

    @Override
    public void onNext(T t) {
        onSuccess(t);
    }

    @Override
    public void onError(Throwable throwable) {
        if (throwable instanceof LifeTreeAPIException) {
            LifeTreeAPIException exception = (LifeTreeAPIException) throwable;
            onFailed(exception.errorCode, throwable.getMessage());
        } else if (throwable instanceof HttpException) {
            HttpException httpException = (HttpException) throwable;
            int code = httpException.code();
            if (code == 500 || code == 404) {
                onFailed(code, "服务器出错");
            }
        } else if (throwable instanceof ConnectException) {
            onFailed(-1, "网络断开,请打开网络!");
        } else if (throwable instanceof SocketTimeoutException) {
            onFailed(-1, "网络连接超时!!");
        } else if (throwable instanceof UnknownHostException) {
            onFailed(-1, "网络断开,请打开网络!");
        } else {
            onFailed(-1, "发生未知错误" + throwable.getMessage());
        }
    }

    @Override
    public void onComplete() {

    }
}
